const jwt = require("jsonwebtoken");
const { JWT_SCRIPT } = require("../config/config.default");
const { tokenExpiredError, invalidToken } = require("../constant/err.type");

const authToken = async (ctx, next) => {
  // console.log(ctx.request.header.authorization);
  const token = ctx.request.header.authorization.replace("Bearer ", ""); //拿到完整的token
  // const { Authorization } = ctx.request.body
  //   console.log(token);

  try {
    // 定义的user = 解析了加密的token  得到了用户信息(id,user_name,is_admin)
    const user = jwt.verify(token, JWT_SCRIPT);
    ctx.state.user = user;
  } catch (err) {
    switch (err.name) {
      case "TokenExpiredError":
        console.log("token已过期", ctx);
        return ctx.app.emit("error", tokenExpiredError, ctx);
      case "JsonWebTokenError":
        console.log("无效的token", ctx);
        return ctx.app.emit("error", invalidToken, ctx);
    }
  }

  await next();
};

module.exports = {
  authToken,
};
